/**
* @description: 临时工单 ==> 发起工单
**/
<template>
  <view class="initiate-task-main">
    <nav-bar class="header" back title="发起工单" @goBack="goBack"/>
    <view class="main-container">
      <!--工单基本信息-->
      <van-form ref="infoForm" validate-trigger="onSubmit">
        <view class="task-info-container">
          <van-cell-group>
            <van-field v-model="taskname" name="taskname" label="工单名称" placeholder="请输入工单名称" required
                       input-align="right" error-message-align="right"
                       :rules="[{ required: true,trigger:'onChange', message: '' }]"/>
            <van-field :value="siteObj.siteName" name="siteName" label="巡视站点" readonly placeholder="请选择巡视站点" required
                       input-align="right" error-message-align="right" right-icon="arrow"
                       :rules="[{ required: true, trigger:'onSubmit', message: '' }]" @click="onOpenSite"/>
            <van-field :value="beginTime" name="beginTime" label="计划开始时间" readonly placeholder="请选择计划开始时间"
                       input-align="right" error-message-align="right" right-icon="arrow" required
                       :rules="[{ required: true, trigger:'onSubmit', message: '' }]"
                       @click="onOpenPicker('beginTime')"/>
            <van-field :value="endTime" name="endTime" label="计划结束时间" readonly placeholder="请选择计划结束时间"
                       input-align="right" error-message-align="right" right-icon="arrow" required
                       :rules="[{ required: true, trigger:'onSubmit', message: '' }]" @click="onOpenPicker('endTime')"/>
            <van-field :value="approver.name" name="approver" label="审批人" readonly placeholder="请选择审批人" input-align="right"
                       error-message-align="right" right-icon="arrow" required
                       :rules="[{ required: true, trigger:'onSubmit', message: '' }]" @click="checkPickerList"/>
          </van-cell-group>
        </view>
        
        <!--工单分配-->
        <plateTitle title="巡视内容分配" :isRequired="true" class="plate-title">
          <van-icon name="add" color="#417ADC" @click="openTypePicker"/>
        </plateTitle>
        <view class="task-assignment-container">
          <view class="task-assignment-item" v-for="(typeItem, typeIndex) in typeColumns" :key="typeIndex">
            <van-collapse v-model="activeName" v-if="typeItem.disabled">
              <van-collapse-item :name="typeItem.name" size="large">
                <template #title>
                  <view class="custom-title">
                    <img src="../../../../static/img/delete.png" alt="" @click="removeType(typeIndex, typeItem.name)">
                    {{ typeItem.text }}
                  </view>
                </template>
                
                <van-field v-model="typeItem.usersText" label="巡视人员" :name="typeItem.fieldNames[0]" clearable
                           clear-trigger="always" placeholder="请选择巡视人员" input-align="right" right-icon="arrow"
                           :rules="[{ required: true, trigger:'onSubmit', message: '' }]" error-message-align="right"
                           @click-right-icon="handleSelectUser(typeItem, typeIndex)"/>
                <van-field v-model="typeItem.equsText" label="巡视内容" :name="typeItem.fieldNames[1]" clearable
                           clear-trigger="always" placeholder="请选择巡视内容" input-align="right" right-icon="arrow"
                           :rules="[{ required: true, trigger:'onSubmit', message: '' }]" error-message-align="right"
                           @click-right-icon="handleSelectEqu(typeItem, typeIndex)"/>
              </van-collapse-item>
            </van-collapse>
          </view>
          <!-- 备注 -->
          <view class="remark-info-container">
            <view>备注</view>
            <van-divider dashed/>
            <div class="remark-wrap">
              <!-- disabled -->
              <textarea class="remark-text" v-model="textareaValue"></textarea>
            </div>
          </view>
        </view>
        <van-button class="submit-btn" block native-type="submit" @click="submitForm">提交</van-button>
      
      </van-form>
      
      <!--审批人选择器-->
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          ref="picker"
          :default-index="defaultPickerIndex"
          show-toolbar
          :columns="currentPickerList"
          cancel-button-text="清空"
          @confirm="pickerConfirm"
          @cancel="pickerEmpty"
        />
      </van-popup>
      
      <!--时间选择器-->
      <van-popup v-model="showDatetimePicker" position="bottom">
        <van-datetime-picker type="datetime" :formatter="pickerFormatter" cancel-button-text="清空"
                             @confirm="onDatetimeConfirm" @cancel="onDatetimeEmpty" v-model="currentDate"
                             :min-date="minDate"/>
      </van-popup>
      
      <!--巡视类型选择器-->
      <van-popup v-model="showTypePicker" position="bottom">
        <van-picker title="巡视项类型" ref="typePicker" show-toolbar :columns="typeColumns" @confirm="onTypeConfirm"
                    @cancel="showTypePicker = false"/>
      </van-popup>
      <!--选择人员选择器-->
      <van-popup v-model="showSelectUser" position="right">
        <selectUser @cancel="userCancel" :equIds="equIds" :selected.sync="staffList"/>
      </van-popup>
      <!--选择站点选择器-->
      <van-popup v-model="showSelectSite" position="right">
        <select-site @cancel="siteCancel" :selected.sync="siteObj" :isInitiateTask="true"/>
      </van-popup>
      <!--选择设备选择器-->
      <van-popup v-model="showSelectEquipment" position="right">
        <select-equipment v-if="showSelectEquipment" :equObj="selectEqumentOption" @cancel="equCancel"
                          :selected.sync="equKeys" @changeSelected="changeEquSelected($event)"/>
      </van-popup>
    </view>
  </view>
</template>

<script>
import navBar from "../../../../components/common/nav-bar";
import plateTitle from "../../../../components/business/plateTitle";
import selectUser from "../../../common/selectUser";
import selectSite from "../../../common/selectSite";
import selectEquipment from "../../../common/selectEquipment";

import {Dialog} from "vant";
import {mapGetters} from "vuex";
import moment from "moment";

export default {
  name: "initiateTask",
  components: {navBar, plateTitle, selectUser, selectSite, selectEquipment},
  data() {
    return {
      staff: "",
      currentDate: "",
      beginTime: "",
      endTime: "",
      approver: {
        name: '',
        id: '',
      },
      showPicker: false,
      defaultPickerIndex: 0,
      currentPickerList: [],
      showDatetimePicker: false,
      showTypePicker: false,
      showSelectUser: false,
      showSelectSite: false,
      showSelectEquipment: false,
      equKeys: [],
      pickerType: "",
      typeColumns: [
        {
          text: "通信设备",
          disabled: true,
          name: "equipment",
          fieldNames: ["equIds", "equs"],
          echoUserField: 'equIds', // 回显详情里的字段
          echoEqusField: 'equs', // 回显详情里设备的字段
          equs: [],
          equsText: "",
          equsCheckbox: [],
          users: [],
          usersText: ""
        },
        {
          text: "通信光缆",
          disabled: true,
          name: "opticalCable",
          fieldNames: ["optIds", "opts"],
          echoEqusField: 'opts', // 回显详情里设备的字段
          echoUserField: 'optIds', // 回显详情里的字段
          equs: [],
          equsText: "",
          equsCheckbox: [],
          users: [],
          usersText: ""
        },
        {
          text: "通信电源",
          disabled: true,
          name: "powerSupply",
          fieldNames: ["powIds", "pows"],
          echoEqusField: 'pows', // 回显详情里设备的字段
          echoUserField: 'powIds', // 回显详情里的字段
          equs: [],
          equsText: "",
          equsCheckbox: [],
          users: [],
          usersText: ""
        }
      ],
      minDate: new Date(0),
      activeName: ["equipment", "opticalCable", "powerSupply"],
      textareaValue: "",
      taskname: "",
      siteObj: {
        siteId: "",
        siteName: ""
      },
      equIds: [], // 通信设备人员
      equText: "",
      optIds: [], // 光缆设备人员
      optText: "",
      powIds: [], // 电源设备人员
      powText: "",
      staffList: {},
      staffIndex: 0,
      staffType: "0",
      selectEqumentOption: {
        equType: "",
        siteId: "",
        isCheckbox: true
      }
    };
  },
  computed: {
    ...mapGetters(["userData"])
  },
  onLoad(e) {
    // 含有taskid和，则认为是再次提交（已经生成的才有taskid）,再次提交的情况，需要进行回显
    if (e.taskId) {
      this.echoFillInfo(e.taskId);
    }
  },
  watch: {
    
    staffList: {
      handler: function (newVal) {
        this.typeColumns[this.staffIndex].users = newVal.ids;
        this.typeColumns[this.staffIndex].usersText = newVal.text;
      },
      immediate: true,
      deep: true
    },
    siteObj: {
      handler: function (newVal, oldVal) {
        console.log("new--val", newVal, oldVal);
        if (oldVal && newVal.siteId !== oldVal.siteId) {
          this.typeColumns.forEach((item, index, arr) => {
            arr[index] = Object.assign({}, item, {
              equs: [],
              equsText: "",
              equsCheckbox: []
            });
          });
          
          // this.typeColumns.map(item => {
          //    Object.assign({}, item, {
          //     equs: [],
          //     equsText: '',
          //     equsCheckbox: []
          //   })
          // })
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.typeColumns.map(item => {
      item.users = [this.userData.userId];
      item.usersText = this.userData.userName;
    });
  },
  methods: {
    // 信息回显
    echoFillInfo (taskId) {
      this.$api.echoPatrolDetails({objId: taskId})
        .then(res => {
          this.taskname = res.data.taskname;
          this.siteObj.siteId = res.data.siteId;
          this.siteObj.siteName = res.data.siteName;
          this.beginTime = moment(res.data.planStartTim).format("YYYY-MM-DD HH:mm");
          this.endTime = moment(res.data.planEndTim).format("YYYY-MM-DD HH:mm");
          this.approver.id = res.data.approvalOperId;
          this.approver.name = res.data.approvalOperName;

         
          for (let i = 0; i < this.typeColumns.length; i++) {
            let typeColumnItem = this.typeColumns[i];
            typeColumnItem.users = res.data[typeColumnItem.echoUserField].map(item => Object.keys(item)[0]); // 人员id数组
            let userValueArr = res.data[typeColumnItem.echoUserField].map(item => Object.values(item)[0]);
            typeColumnItem.usersText = userValueArr.length > 3
              ? userValueArr.slice(0, 3).reduce((prev, item) => {
                prev += item + ','
                return prev;
              }, '')
              : userValueArr.reduce((prev, item) => {
                prev += item + ','
                return prev;
              }, '');
            typeColumnItem.equsCheckbox = res.data[typeColumnItem.echoEqusField].map(item => {
              return {ORGID: item}
            });
            typeColumnItem.equs = res.data[typeColumnItem.echoEqusField]; // 设备的数组
            typeColumnItem.equsText = `已选择${res.data[typeColumnItem.echoEqusField].length}个`;
          }
          
          
        })
    },
    // 选择设备
    changeEquSelected(value) {
      this.showSelectEquipment = false;
      if (this.selectEqumentOption.isCheckbox) {
        // 多选
        // 返回数组
        this.typeColumns[this.staffIndex].equsCheckbox = value;
        this.typeColumns[this.staffIndex].equs = value.map(item => {
          return item.ORGID;
        });
        const equSelect = value.map(item => {
          return item.NAME;
        });
        this.typeColumns[this.staffIndex].equsText =
          equSelect.length > 0 ? `已选择 ${equSelect.length} 个` : "";
        // if (equSelect.length > 2) {
        //   const firstPeple = equSelect.slice(0, 3).toString()
        //   this.typeColumns[this.staffIndex].equsText =
        //     firstPeple + `等${equSelect.length}人`
        // } else {
        //   this.typeColumns[this.staffIndex].equsText = equSelect.toString()
        // }
      } else {
        // 单选
        this.typeColumns[this.staffIndex].equsText = value.NAME;
        this.typeColumns[this.staffIndex].equs = [value.ORGID];
      }
    },
    handleSelectEqu(e, i) {
      if (this.siteObj.siteId) {
        this.selectEqumentOption = {
          equType: e.name,
          siteId: this.siteObj.siteId,
          isCheckbox: true
        };
        // this.equKeys = []
        this.staffIndex = i;
        this.equKeys = e.equsCheckbox;
        this.showSelectEquipment = true;
      } else {
        Dialog.alert({
          title: "提示",
          message: "请先选择巡视站点"
        }).then(() => {
          // on close
        });
      }
    },
    equCancel() {
      this.showSelectEquipment = false;
    },
    // 选择人员
    handleSelectUser(e, i) {
      this.staffIndex = i;
      this.staffList = {
        ids: !e.usersText ? [] : e.users,
        text: e.usersText
      };
      
      this.showSelectUser = true;
    },
    userCancel() {
      this.showSelectUser = false;
    },
    // 选择站点
    onOpenSite() {
      this.showSelectSite = true;
    },
    siteCancel() {
      this.showSelectSite = false;
    },
    // 获取审批人下拉列表
    checkPickerList() {
      this.$api.getApprover({orgId: this.userData.orgId}).then(res => {
        if (res.code === 0) {
          this.showPicker = true;

          this.$nextTick(() => {
            this.currentPickerList = res.data.map((item, index) => {
              if (item.approvalOperId === this.approver.id) {
                this.defaultPickerIndex = index;
                this.$refs.picker.setColumnIndex(0, index);
              }
              return {
                text: item.approvalOperName,
                value: item.approvalOperId,
              };
            });
          })
          
        }
      });
    },
    // picker确认选择
    pickerConfirm(selectedOption) {
      this.approver.id = selectedOption.value;
      this.approver.name = selectedOption.text;
      this.showPicker = false;
    },
    // 清空已选
    pickerEmpty(selectedOption) {
      this.showPicker = false;
      this.approver.id = '';
      this.approver.name = '';
      if(selectedOption !== undefined) {
        selectedOption.text = "";
        selectedOption.value = "";
      }
    },
    onOpenPicker(pickerType) {
      if (pickerType === "beginTime") {
        this.currentDate =
          this.beginTime !== "" ? new Date(this.beginTime) : new Date();
      } else if (pickerType === "endTime") {
        this.currentDate =
          this.endTime !== "" ? new Date(this.endTime) : new Date();
      }
      this.pickerType = pickerType;
      this.showDatetimePicker = true;
    },
    onDatetimeConfirm(time) {
      let timeString = moment(time).format("YYYY-MM-DD HH:mm");
      if (this.pickerType === "beginTime") {
        this.beginTime = timeString;
        if (
          this.endTime !== "" &&
          new Date(this.endTime).getTime() < new Date(this.beginTime).getTime()
        ) {
          Dialog.alert({
            message: "计划开始时间不可晚于计划结束时间",
            theme: "round-button"
          });
          this.beginTime = "";
        }
      } else if (this.pickerType === "endTime") {
        this.endTime = timeString;
        if (
          this.beginTime !== "" &&
          new Date(this.endTime).getTime() < new Date(this.beginTime).getTime()
        ) {
          Dialog.alert({
            message: "计划结束时间不可早于计划开始时间",
            theme: "round-button"
          });
          this.endTime = "";
        }
      }
      this.showDatetimePicker = false;
    },
    onDatetimeEmpty() {
      this.showDatetimePicker = false;
      this.pickerType === "beginTime" && (this.beginTime = "");
      this.pickerType === "endTime" && (this.endTime = "");
    },
    pickerFormatter(type, val) {
      if (type === "year") return val + "年";
      if (type === "month") return val + "月";
      if (type === "day") return val + "日";
      if (type === "hour") return val + "时";
      if (type === "minute") return val + "分";
    },
    onTypeConfirm(type, index) {
      // this.typeColumns[index].disabled = true
      this.typeColumns[index] = Object.assign({}, this.typeColumns[index], {
        disabled: true,
        equs: [],
        equsText: "",
        equsCheckbox: [],
        users: [this.userData.userId],
        usersText: this.userData.userName
      });
      this.$refs.typePicker.setColumnValues(0, this.typeColumns);
      
      this.showTypePicker = false;
    },
    // 删除某类型的内容
    removeType(index, name) {
      // this.typeColumns[index].disabled = false
      this.typeColumns[index] = Object.assign({}, this.typeColumns[index], {
        disabled: false,
        equs: [],
        equsText: "",
        equsCheckbox: [],
        users: [],
        usersText: ""
      });
      // this.$refs.typePicker.setColumnValues(0, this.typeColumns)
    },
    openTypePicker() {
      this.showTypePicker = true;
      this.$nextTick(() => {
        this.$refs.typePicker.setColumnValues(0, this.typeColumns);
      });
    },
    goBack() {
      // uni.navigateBack()
      uni.navigateTo({
        url: "/pages/workBench/temporaryTask/taskMonitor/patrolTaskMonitor"
      });
    },
    async submitForm() {
      // console.log('2356789', this.$refs.infoForm.validate())
      await this.$refs.infoForm
        .validate()
        .then(res => {
          // on confirm
          let params = {
            taskname: this.taskname,
            siteId: this.siteObj.siteId,
            siteName: this.siteObj.siteName,
            planStartTim: moment(this.beginTime).format("YYYY-MM-DD HH:mm:ss"),
            planEndTim: moment(this.endTime).format("YYYY-MM-DD HH:mm:ss"),
            receiveTime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
            // 登录用户信息
            userId: this.userData.userId,
            userName: this.userData.userName,
            orgId: this.userData.orgId,
            batchId: this.userData.batchId,
            
            remark: this.textareaValue,
  
            approvalOperName: this.approver.name, // 审批人姓名
            approvalOperId: this.approver.id,   // 审批人id
          };
          this.typeColumns.filter(item => {
            if (item.name === "equipment") {
              params["equIds"] = item.users;1
              params["equs"] = item.equs;
            } else if (item.name === "powerSupply") {
              params["powIds"] = item.users;
              params["pows"] = item.equs;
            } else {
              params["optIds"] = item.users;
              params["opts"] = item.equs;
            }
          });
          
          this.$api.getTaskAllo(params).then(res => {
            if (res.code == 0) {
              Dialog.confirm({
                message: "保存成功，是否继续发起工单？",
                cancelButtonText: "返回列表",
                confirmButtonText: "继续发起"
              })
                .then(() => {
                  uni.navigateTo({
                    url: "/pages/workBench/temporaryTask/initiateTask/initiateTask"
                  });
                })
                .catch(() => {
                  // on cancel
                  uni.navigateTo({
                    url: "/pages/workBench/temporaryTask/taskMonitor/patrolTaskMonitor"
                  });
                });
            }
          });
        })
        .catch(() => {
        });
    }
  }
};
</script>

<style scoped lang="scss">
.initiate-task-main {
  min-height: 100vh;
  background-color: #f2f6fa;
  
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  
  .main-container {
    height: calc(100vh - #{px2vh(386)});
    padding: px2vh(30) px2vw(30) px2vh(30) px2vw(30);
    overflow: auto;
    
    /deep/ .van-field {
      .van-field__label,
      .van-field__control:read-only {
        // font-size: px2vh(36);
      }
      
      .van-field__right-icon {
        color: #bebebe;
      }
    }
    
    .task-info-container,
    .task-assignment-item {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #ffffff;
      
      /deep/ .van-field__body {
        .van-field__control--right {
          font-size: px2vw(42);
        }
        
        .van-icon-clear::before {
          // color: #ff4355;
        }
      }
    }
    
    .plate-title {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
      
      /deep/ .plate-title-left .plate-title-text {
        font-size: px2vw(42);
      }
    }
    
    .task-assignment-container {
      .task-assignment-item {
        margin-bottom: px2vh(30);
        
        .custom-title {
          display: flex;
          align-items: center;
          
          img {
            width: px2vh(42);
            margin-right: px2vw(29);
          }
        }
        
        /deep/ .van-field__body {
          .van-field__control--right {
            pointer-events: none;
            // font-size: px2vh(36);
          }
          
          .van-icon-clear::before {
            // color: #ff4355;
          }
        }
        
        /deep/ .van-collapse-item__content {
          padding: 0;
        }
        
        /deep/ .van-cell--large .van-cell__title {
          font-size: px2vw(42);
        }
      }
      
      .remark-info-container {
        padding: px2vh(42) px2vw(50) px2vh(70);
        font-size: px2vw(42);
        color: #666666;
        border-radius: $border-radius-base;
        overflow: hidden;
        background-color: #ffffff;
        margin: px2vh(30) 0;
        
        .remark-wrap {
          background-color: #fafafa;
          padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
          border-radius: px2vw(20);
          
          .remark-text {
            height: px2vh(150);
          }
        }
      }
    }
  }
  
  /deep/ .van-button.submit-btn {
    position: fixed;
    bottom: px2vh(20);
    margin: px2vh(30) auto 0;
    width: calc(100vw - #{px2vw(60)});
    height: px2vh(120);
    color: #fff;
    background-color: #417adc;
    border: 1px solid #417adc;
    border-radius: px2vh(60);
  }
}
</style>